import axios from 'axios'
import { Message } from 'element-ui'

const axiosInstance = axios.create({
  baseURL: 'http://localhost:8070/api',
  timeout: 20000, // request timeout
  withCredentials: true
})

// request interceptor
axiosInstance.interceptors.request.use(
  config => {
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
axiosInstance.interceptors.response.use(
  response => {
    const res = response.data
    console.log(res.code)
    if (res.code !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error'
      })
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default axiosInstance
